﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace PCE.Mvc.Extensions
{
	public static class HtmlHelperExtensions
	{
		private static readonly IDictionary<bool, string> BoolNames = new Dictionary<bool, string> {
			{ true, "Да" },
			{ false, "Нет" }
		};
		
		public static MvcHtmlString EnumDropDrownListFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> selector)
		{
			var type = typeof (TProperty);

			if (!type.IsEnum)
				throw new ArgumentException("passed type must be of Enum type", "enumerationValue");

			return helper.DropDownListFor(
				selector,
				Enum
					.GetValues(type)
					.Cast<Enum>()
					.Select(e => new SelectListItem
					{
						Value = e.ToString(),
						Text = e.GetDescription()
					})
			);
		}

		public static MvcHtmlString BoolDropDownListFor<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, bool>> selector)
		{
			return helper.DropDownListFor(
				selector,
				BoolNames.Select(p => new SelectListItem { Value = p.Key.ToString(), Text = p.Value })
			);
		}

		public static MvcHtmlString BoolDropDownListFor<TModel>(this HtmlHelper<TModel> helper, Expression<Func<TModel, bool?>> selector)
		{
			return helper.DropDownListFor(
				selector,
				new[] { new SelectListItem { Value = string.Empty, Text = string.Empty } }
				.Union(BoolNames.Select(p => new SelectListItem { Value = p.Key.ToString(), Text = p.Value }))
			);
		}

		public static MvcHtmlString GetDescription(this bool? value)
		{
			return 
				value.HasValue 
				? new MvcHtmlString(BoolNames[value.Value]) 
				: new MvcHtmlString(string.Empty);
		}

		public static MvcHtmlString GetDescription(this bool value)
		{
			return new MvcHtmlString(BoolNames[value]);
		}

		public static string GetDescription(this Enum value)
		{
			var fi = value.GetType().GetField(value.ToString());
			var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
			return attributes.Length > 0 ? attributes[0].Description : value.ToString();
		}
	}
}